package cn.sx.yys.blog.controller;

import cn.sx.yys.utils.NetworkUtil;
import com.google.code.kaptcha.impl.DefaultKaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * 图形验证码控制器
 *
 * @author 猿帅
 * @email 1603194187@qq.com
 * @date 2021/2/5 17:14
 */
@RestController
@RequestMapping("/img")
public class KaptchaController {
    @Autowired
    private DefaultKaptcha defaultKaptcha;
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/code")
    public void defaultKaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException{
        response.setHeader("Cache-Control", "no-store, no-cache");
        response.setContentType("image/jpeg");

        // 生成文字验证码
        String text = defaultKaptcha.createText();
        // 生成图片验证码
        BufferedImage image = defaultKaptcha.createImage(text);
        // 这里我们使用redis缓存验证码的值，并设置过期时间为60秒
        String ipAddress = NetworkUtil.getIpAddress(request);
        redisTemplate.opsForValue().set(ipAddress+"imgCode",text,10, TimeUnit.MINUTES);
        HttpSession session = request.getSession();
        session.setAttribute("imgCode",text);

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image, "jpg", out);
        out.flush();
        out.close();
    }
}
